package cn.iocoder.yudao.module.erp.service.erpSupplierguide;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductVO;
import cn.iocoder.yudao.module.erp.controller.app.erpSupplierguide.vo.ErpSupplierGuideUpdateReqVO;
import cn.iocoder.yudao.module.erp.controller.app.erpSupplierguide.vo.SupplierGuideImportExcelVO;
import cn.iocoder.yudao.module.erp.controller.app.erpSupplierguide.vo.SupplierGuideImportRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.purchase.ErpSupplierMapper;
import cn.iocoder.yudao.module.erp.enums.ErpSupplierStatus;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.erp.controller.admin.erpSupplierguide.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.erpSupplierguide.ErpSupplierGuideDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.erpSupplierguide.ErpSupplierGuideMapper;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.UNAUTHORIZED;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * ERP 供应商指导价 Service 实现类
 *
 * @author xc
 */
@Service
@Validated
public class ErpSupplierGuideServiceImpl implements ErpSupplierGuideService {

    @Resource
    private ErpSupplierGuideMapper supplierGuideMapper;
    @Resource
    private ErpSupplierMapper erpSupplierMapper;
    @Resource
    private ErpProductMapper erpProductMapper;



    @Override
    public Long createSupplierGuide(ErpSupplierGuideSaveReqVO createReqVO) {
        // 插入
        ErpSupplierGuideDO supplierGuide = BeanUtils.toBean(createReqVO, ErpSupplierGuideDO.class);
        supplierGuideMapper.insert(supplierGuide);
        // 返回
        return supplierGuide.getId();
    }

    @Override
    public void updateSupplierGuide(ErpSupplierGuideSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplierGuideExists(updateReqVO.getId());
        // 更新
        ErpSupplierGuideDO updateObj = BeanUtils.toBean(updateReqVO, ErpSupplierGuideDO.class);
        supplierGuideMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplierGuide(Long id) {
        // 校验存在
        validateSupplierGuideExists(id);
        // 删除
        supplierGuideMapper.deleteById(id);
    }

    @Override
        public void deleteSupplierGuideListByIds(List<Long> ids) {
        // 校验存在
        validateSupplierGuideExists(ids);
        // 删除
        supplierGuideMapper.deleteByIds(ids);
        }

    private void validateSupplierGuideExists(List<Long> ids) {
        List<ErpSupplierGuideDO> list = supplierGuideMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(SUPPLIER_GUIDE_NOT_EXISTS);
        }
    }

    private void validateSupplierGuideExists(Long id) {
        if (supplierGuideMapper.selectById(id) == null) {
            throw exception(SUPPLIER_GUIDE_NOT_EXISTS);
        }
    }

    @Override
    public ErpSupplierGuideDO getSupplierGuide(Long id) {
        return supplierGuideMapper.selectById(id);
    }

    @Override
    public PageResult<ErpSupplierGuideDO> getSupplierGuidePage(ErpSupplierGuidePageReqVO pageReqVO) {
        return supplierGuideMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<ErpSupplierGuideDO> getAppSupplierGuidePage(PageParam pageReqVO) {
        return supplierGuideMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ErpSupplierGuideDO> exportSupplierGuideExcel() {
        if(getLoginUserId() == null){
            throw exception(UNAUTHORIZED);
        }

        return supplierGuideMapper.selectList(
                new LambdaQueryWrapperX<ErpSupplierGuideDO>()
                        .eq(ErpSupplierGuideDO::getSupplierId, getLoginUserId())
        );
    }


    @Override
    public SupplierGuideImportRespVO importList(List<SupplierGuideImportExcelVO> list) {
        SupplierGuideImportRespVO respVO = SupplierGuideImportRespVO.builder().failList(new ArrayList<>()).build();
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(SUPPLIER_IMPORT_EMPTY);
        }
        if(getLoginUserId() == null){
            throw exception(UNAUTHORIZED);
        }

        //查询产品物料表
        List<ErpProductVO> erpProductDOS = erpProductMapper.selectAllProductList();
        //转为map，key为name，value为unit
        Map<String, String> productMap = erpProductDOS.stream().collect(Collectors.toMap(ErpProductVO::getName, ErpProductVO::getUnit));

        Map<String, String> addMap = new HashMap<>();

        List<ErpSupplierGuideDO> beanList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            SupplierGuideImportExcelVO item = list.get(i);
            try {
                ValidationUtils.validate(BeanUtils.toBean(item, ErpSupplierGuideSaveReqVO.class));
            } catch (ConstraintViolationException ex) {
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getName() + " 导入失败：" + ex.getMessage());
                break;
            }
            //需要与物料产品表匹配校验
            if(!productMap.containsKey(item.getName())){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getName() + " 导入失败：不存在该产品");
                break;
            }
            if(!item.getUnit().equals(productMap.get(item.getName()))){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getName() + " 导入失败：单位不匹配,应该为"+ productMap.get(item.getName()));
                break;
            }
            if(addMap.containsKey(item.getName())){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getName() + " 导入失败：产品重复");
                break;
            }

            //转换DO
            ErpSupplierGuideDO bean = BeanUtils.toBean(item, ErpSupplierGuideDO.class);
            bean.setSupplierId(getLoginUserId());
            beanList.add(bean);
            addMap.put(item.getName(), item.getUnit());
        }
        if(respVO.getFailList().isEmpty()){
            deleteSupplierGuideBySupplierId();
            supplierGuideMapper.insert(beanList);
        }
        return respVO;
    }

    @Override
    public void deleteSupplierGuideBySupplierId() {
        if(getLoginUserId() == null){
            throw exception(UNAUTHORIZED);
        }
        supplierGuideMapper.delete(
                new LambdaQueryWrapperX<ErpSupplierGuideDO>()
                       .eq(ErpSupplierGuideDO::getSupplierId, getLoginUserId())
        );
    }

    @Override
    public void checkSupplierStatus(){
        if(getLoginUserId() == null){
            throw exception(UNAUTHORIZED);
        }
        ErpSupplierDO erpSupplierDO = erpSupplierMapper.selectById(getLoginUserId());
        if(erpSupplierDO == null){
            throw exception(SUPPLIER_NOT_EXISTS);
        }
        if(!ErpSupplierStatus.WAIT_AUDIT.getStatus().equals(erpSupplierDO.getStatus())){
            throw exception(SUPPLIER_CAN_NOT_EXCHANGE);
        }
    }

    @Override
    public void updateAppSupplierGuide(ErpSupplierGuideUpdateReqVO updateReqVO) {
        // 校验存在
        validateSupplierGuideExists(updateReqVO.getId());
        // 更新
        ErpSupplierGuideDO updateObj = BeanUtils.toBean(updateReqVO, ErpSupplierGuideDO.class);
        supplierGuideMapper.updateById(updateObj);
    }


}
